package com.example.test.dialogfactory;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Process;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity39 extends AppCompatActivity {

    private TextView mUid;
    private EditText mEdit;
    private Button mSave;
    private Button mRead;
    private Button mReadApp;

    public static void start( Context context ) {

        Intent starter = new Intent( context, MainActivity39.class );
        context.startActivity( starter );
    }

    @Override
    protected void onCreate( Bundle savedInstanceState ) {

        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main39 );
        initView();
        initViewAction();
    }

    private void initView() {

        mUid = (TextView) findViewById( R.id.uid );
        mEdit = (EditText) findViewById( R.id.edit );
        mSave = (Button) findViewById( R.id.save );
        mRead = (Button) findViewById( R.id.read );
        mReadApp = (Button) findViewById( R.id.readApp );
    }

    private void initViewAction() {

        mUid.setText( "Uid: " + Process.myUid() );

        mSave.setOnClickListener( new OnClickListener() {
            @Override
            public void onClick( View view ) {

                Editable text = mEdit.getText();
                if ( TextUtils.isEmpty( text ) ) {
                    return;
                }
                SharedPreferences preferences = getSharedPreferences( "UID", Context.MODE_PRIVATE );
                preferences.edit().putString( "test", text.toString() ).apply();
                mEdit.setText( "" );
            }
        } );

        mRead.setOnClickListener( new OnClickListener() {
            @Override
            public void onClick( View view ) {

                SharedPreferences preferences = getSharedPreferences( "UID", Context.MODE_PRIVATE );
                String s = preferences.getString( "test", "没有获取到" );
                mEdit.setText( s );
            }
        } );

        mReadApp.setOnClickListener( new OnClickListener() {
            @Override
            public void onClick( View view ) {

                try {
                    Context ct = createPackageContext( "com.example.test.uidapp", Context.CONTEXT_IGNORE_SECURITY );
                    SharedPreferences preferences = ct.getSharedPreferences( "UID", Context.MODE_PRIVATE );
                    String s = preferences.getString( "test", "没有获取到" );
                    mEdit.setText( s );
                } catch ( Exception e ) {
                    e.printStackTrace();
                }
            }
        } );
    }
}